import { ExecutionContext, Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Observable } from 'rxjs';
import { UnauthorizedException } from '@nestjs/common';

type JwtAuthGuardOptions = {
  optional: boolean;
};

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  private _customOptions: JwtAuthGuardOptions = { optional: false };

  constructor(options?: JwtAuthGuardOptions) {
    super();
    this._customOptions = { ...this._customOptions, ...options };
  }

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    return (super.canActivate(context) as Promise<boolean>).catch((e) => {
      console.log(e);
      if (!this._customOptions.optional) throw new UnauthorizedException();
      return true;
    });
  }
}
